package net.sakz.oss;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SSOShiro extends AuthenticatingFilter {
	private static Logger logger = LoggerFactory.getLogger(SSOShiro.class);
	private static final String TOKEN_PARAMETER = "token";
	public static final String DEFAULT_ERROR_KEY_ATTRIBUTE_NAME = "shiroSSOLoginFailure";
	public static final String DEFAULT_KEY_ATTRIBUTE_NAME = "userInfo";
	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse arg1) throws Exception {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String token = httpRequest.getParameter(TOKEN_PARAMETER);
		return new SSOToken(token);
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		return executeLogin(request, response);
	}

	@Override
	protected boolean isLoginRequest(ServletRequest request, ServletResponse response) {
		// TODO Auto-generated method stub
		return super.isLoginRequest(request, response);
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		if(request instanceof HttpServletRequest) {
			((HttpServletRequest)request).getSession().setAttribute(DEFAULT_KEY_ATTRIBUTE_NAME, subject.getPrincipals().asList().get(1));
		}
		issueSuccessRedirect(request, response);
		return false;
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		setFailureAttribute(request, e);
		return true;
	}

	protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
		String className = ae.getClass().getName();
		request.setAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, className);
	}
}
